package com.gitee.wsl.ext.array

import kotlin.math.max
import kotlin.math.min


/**
 * The maximum array size for the methods in this class: {@value}.
 */
private val MAX_ARRAY_SIZE: Int = Int.Companion.MAX_VALUE - 8

/**
 * Ensure the array can add an element at the specified index.
 *
 * @param array the array to check.
 * @param index the index to add at.
 * @return the array or a newly allocated copy of the array.
 */
fun IntArray.ensureCapacity(index: Int): IntArray {
    if (index >= size) {
        return copyOf( min(MAX_ARRAY_SIZE.toLong(), max(size * 2L, (index + 1).toLong())).toInt())
    }
    return this
}

fun LongArray.ensureCapacity(index: Int): LongArray {
    if (index >= size) {
        return copyOf( min(MAX_ARRAY_SIZE.toLong(), max(size * 2L, (index + 1).toLong())).toInt())
    }
    return this
}

fun ShortArray.ensureCapacity(index: Int): ShortArray {
    if (index >= size) {
        return copyOf( min(MAX_ARRAY_SIZE.toLong(), max(size * 2L, (index + 1).toLong())).toInt())
    }
    return this
}

fun CharArray.ensureCapacity(index: Int): CharArray {
    if (index >= size) {
        return copyOf( min(MAX_ARRAY_SIZE.toLong(), max(size * 2L, (index + 1).toLong())).toInt())
    }
    return this
}

fun <T> Array<T?>.ensureCapacity(index: Int): Array<T?> {
    if (index >= size) {
        return copyOf( min(MAX_ARRAY_SIZE.toLong(), max(size * 2L, (index + 1).toLong())).toInt())
    }
    return this
}